<template>
  <div>
    <a-modal
      v-model:visible="uploadModal"
      title="上传文件"
      :unmount-on-close="true"
      :mask-closable="false"
      width="420px"
      @cancel="handleCancel"
      @before-close="handleBeforeClose"
    >
      <chunk-upload
        ref="uploadRef"
        :value="fileGroup"
        :file-num-limit="9"
        is-multiple
        :disable="disableUpload"
        @file-change="handleFileChange"
        @upload-success="handleUploadSuccess"
        @upload-error="handleUploadError"
      >
        <template #default>
          <div class="arco-upload-wrapper arco-upload-wrapper-type-picture">
            <span class="arco-upload arco-upload-draggable">
              <div class="arco-upload-drag">
                <svg
                  viewBox="0 0 48 48"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                  stroke="currentColor"
                  class="arco-icon arco-icon-plus"
                  stroke-width="4"
                  stroke-linecap="butt"
                  stroke-linejoin="miter"
                >
                  <path d="M5 24h38M24 5v38"></path>
                </svg>
                <div class="arco-upload-drag-text"></div>
              </div>
            </span>
          </div>
        </template>
      </chunk-upload>
      <template #footer>
        <div class="footer">
          <span>共{{ fileList.length }}个文件</span>
          <a-space>
            <a-button @click="handleCancel">取消</a-button>
            <a-button id="picker" type="primary" @click="handleSubmit"
              >确认上传</a-button
            >
          </a-space>
        </div>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import useFileManageStore from '@/store/modules/file-manage/index';
  import { storeToRefs } from 'pinia';
  import type { FileItem } from '@arco-design/web-vue/es/upload/interfaces';
  import ChunkUpload from '@/components/chunk-upload/index.vue';
  // import plusIcon from '@/assets/images/file-manager/plus.png';
  import pngIcon from '@/assets/images/file-manager/png.png';
  import jpgIcon from '@/assets/images/file-manager/jpg.png';
  import docIcon from '@/assets/images/file-manager/doc.png';
  import xlsIcon from '@/assets/images/file-manager/xls.png';
  import rvtIcon from '@/assets/images/file-manager/rvt.png';
  import otherIcon from '@/assets/images/file-manager/other.png';
  import { addFile } from '../api';

  // import { FileMessage } from '@/api/tree-folder';
  const store = useFileManageStore();
  const { uploadModal, selectedFolder } = storeToRefs(store);

  const uploadRef = ref<any>(null);
  // eslint-disable-next-line no-undef
  const fileList = ref<WebUploader.File[]>([]);
  let uploadedCount = 0;
  const disableUpload = ref(false);
  const fileGroup = ref('');

  // 获取文件图标
  const getFileIcon = (fileName: string) => {
    const suffix = fileName.split('.')[1];
    let fileIcon = null;
    switch (suffix) {
      case 'png':
        fileIcon = pngIcon;
        break;
      case 'jpg':
      case 'jpeg':
        fileIcon = jpgIcon;
        break;
      case 'doc':
      case 'docx':
        fileIcon = docIcon;
        break;
      case 'xls':
      case 'xlsx':
        fileIcon = xlsIcon;
        break;
      case 'rvt':
        fileIcon = rvtIcon;
        break;
      default:
        fileIcon = otherIcon;
    }

    return fileIcon;
  };

  // eslint-disable-next-line no-undef
  const handleFileChange = (fileItemList: WebUploader.File[]) => {
    fileList.value = fileItemList;
  };

  // 保存文件信息
  const handleAdd = () => {
    const promiseList: any[] = [];
    fileList.value.forEach((file) => {
      const params = {
        projectId: selectedFolder.value?.projectId || '',
        teamId: selectedFolder.value?.teamId || '',
        folderId: selectedFolder.value?.id || '',
        name: file.name,
        size: file.size,
        fileToken: file.fileToken,
        description: file.description,
      };
      promiseList.push(addFile(params));

      Promise.all(promiseList).then((resArr) => {
        console.log(resArr);
        let result = true;
        resArr.forEach((res) => {
          if (!res.status) result = false;
        });
        if (result) {
          Message.success('提交成功');
          store.setUploadModal(false);
        }
      });
    });
  };

  // 处理文件上传成功事件
  const handleUploadSuccess = (file: any, res: any) => {
    console.log('succ: ', file, res);
    uploadedCount++;
    if (uploadedCount === fileList.value.length) {
      // 所有文件上传成功，保存文件信息
      handleAdd();
    }
  };

  // 文件上传失败
  const handleUploadError = (failType: any, file: any, res: any) => {
    console.log('err: ', failType, file, res);
  };

  // 上传按钮点击事件
  const handleSubmit = () => {
    console.log(uploadRef.value.getFilesInfo());
    disableUpload.value = true;
    uploadRef.value.submit();
  };

  // 弹窗关闭前，清空数据
  const handleBeforeClose = () => {
    fileList.value = [];
    uploadedCount = 0;
    disableUpload.value = false;
    fileGroup.value = '';
  };

  // 取消按钮点击事件
  const handleCancel = () => {
    store.setUploadModal(false);
  };

  const handleSuccess = (fileItem: FileItem) => {};

  const handleError = (fileItem: FileItem) => {};
</script>

<style lang="less" scoped>
  /* 覆盖文件拖拽上传默认样式 */
  :deep(.arco-upload-drag) {
    padding: 40px 0;
    background-color: var(--color-fill-2);
    border-radius: var(--border-radius-medium);

    .arco-upload-drag-text::before {
      content: '点击或拖拽文件到此处上传';
    }
  }

  /* 拖动文件到拖动框内样式 */
  :deep(.webuploader-dnd-over) {
    .arco-upload-drag {
      border: 1px dashed rgb(var(--primary-6));
      svg {
        color: rgb(var(--primary-6));
      }

      .arco-upload-drag-text::before {
        content: '释放文件';
      }
    }
  }

  /* 拖动框hover样式 */
  :deep(.webuploader-pick-hover) {
    .arco-upload-drag {
      border: 1px dashed var(--color-neutral-4);
    }
  }

  .footer {
    display: flex;
    justify-content: space-between;
    align-items: center;

    span {
      color: var(--color-text-2);
    }

    button {
      border-radius: var(--border-radius-medium);
    }
  }
</style>
